﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Web;
using FrienDev.Data;
using WindowsLive;
using FrienDev.SystemApps;

namespace FrienDev.BusinessRules
{
    public class UserRules
    {
        private static UserRules _instance;

        public static UserRules Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new UserRules();
                }
                return _instance;
            }
        }


        private FrienDevDataContext m_DataContext = FrienDevDataContext.Instance;

        private UserRules()
        {
        }

        /// <summary>
        /// 判断用户是否已经登录
        /// </summary>
        public bool IsCurrentUserLogined
        {
            get
            {
                if (HttpContext.Current.Session[ApplicationSettings.SESSIONUSERIDKEY] == null)
                {
                    // 测试用代码
                    //OnlineRules.Instance.UserLogin("c180360bef7a4ffe5b514285aba649e3");
                    return false;
                }
                return true;
            }
        }

        /// <summary>
        /// 从客户端Cookie中获得UserId
        /// </summary>
        /// <returns></returns>
        private string GetUserIdFromCookie()
        {
            string userId = "";

            /* If the user token has been cached in a site cookie, attempt
                to process it and extract the user ID. */
            HttpRequest req = HttpContext.Current.Request;
            HttpCookie loginCookie = req.Cookies[ApplicationSettings.LOGINCOOKIE];

            if (loginCookie != null)
            {
                string token = loginCookie.Value;
                if (!string.IsNullOrEmpty(token))
                {
                    WindowsLiveLogin.User user = ApplicationSettings.WindowsLiveLogin.ProcessToken(token);

                    if (user != null)
                    {
                        userId = user.Id;
                    }
                }
            }
            return userId;
        }

        /// <summary>
        /// 获得当前用户的UserId
        /// </summary>
        /// <returns></returns>
        public string GetCurrentUserId()
        {
            if (!IsCurrentUserLogined)
            {
                throw new Exception("User didn't login yet.");
            }
            return HttpContext.Current.Session[ApplicationSettings.SESSIONUSERIDKEY].ToString();
        }

        public User GetCurrentUser()
        {
            IEnumerable<User> users = from u in m_DataContext.Users
                                      where u.UserId == GetCurrentUserId()
                                      select u;
            User user = users.SingleOrDefault();
            if (user == null)
            {
                HttpContext context = HttpContext.Current;
                context.Response.Redirect("/home/registration.aspx");
                context.Response.End();
            }
            return users.SingleOrDefault();
        }

        /// <summary>
        ///  判断用户是否已经注册
        /// </summary>
        /// <returns></returns>
        public User IsUserRegisted()
        {
            IEnumerable<User> users = from u in m_DataContext.Users
                                      where u.UserId == GetCurrentUserId()
                                      select u;
            return users.SingleOrDefault();
        }

        public void UpdateUserLoginInfomation()
        {
            User user = GetCurrentUser();
            user.LastLoginDateTime = DateTime.Now;
            user.LastLoginIp = HttpContext.Current.Request.UserHostAddress;
            user.VisitTotal = user.VisitTotal.HasValue ? user.VisitTotal + 1 : 1;
            m_DataContext.SubmitChanges(ConflictMode.ContinueOnConflict);
        }

        /// <summary>
        /// 注册用户信息
        /// </summary>
        /// <param name="name"></param>
        /// <param name="email"></param>
        /// <param name="gender"></param>
        /// <param name="birthday"></param>
        public void InsertUserBasicInfo(string name, string email, bool gender, DateTime birthday, string ft, string description)
        {
            User user = new User
            {
                UserId = GetCurrentUserId(),
                FullName = name,
                Email = email,
                Gender = gender,
                Birthday = birthday,
                FavoriteTechnical = ft,
                Description = description
            };
            m_DataContext.Users.InsertOnSubmit(user);
            foreach (Application app in ApplicationRules.Instance.GetAllDefaultApplication())
            {
                UserApplication userApp = new UserApplication() { Application = app, User = user };
                m_DataContext.Users.InsertOnSubmit(user);
            }
            m_DataContext.SubmitChanges();
        }

        /// <summary>
        /// 判断Email是否唯一(注册时)
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public bool EmailUnique(string email)
        {
            IEnumerable<User> users = from u in m_DataContext.Users
                                      where u.Email.ToString().Trim() == email.ToString().Trim()
                                      select u;
            if (users.Count() > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 判断Email是否唯一(更新时)
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public bool EmailUniqueExceptSelf(string email)
        {
            IEnumerable<User> users = from u in m_DataContext.Users
                                      where u.Email.ToString().Trim() == email.ToString().Trim() && u.UserId != GetCurrentUserId()
                                      select u;
            if (users.Count() > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 更新用户基本信息
        /// </summary>
        /// <param name="name"></param>
        /// <param name="email"></param>
        /// <param name="gender"></param>
        /// <param name="birthday"></param>
        /// <param name="ft"></param>
        /// <param name="description"></param>
        public void UpdateUserBasicInfo(string email, bool gender, DateTime birthday, string ft, string description)
        {
            User user = GetCurrentUser();
            user.Email = email;
            user.Gender = gender;
            user.Birthday = birthday;
            user.FavoriteTechnical = ft;
            user.Description = description;
            AddUserEditInfoTrack(user.UserId,2);
            m_DataContext.SubmitChanges();
        }

        public void AddUserImageUpdateTrack(string userId)
        {
            string logoUrl = ApiHelper.Instance.GetUserLogoUrl(userId);
            string homePageLnk = ApiHelper.Instance.GetUserHomepageLink(userId);
            ApiHelper.Instance.AppendTodayTrack(userId,typeof(FriendApplication), 1, new string[] { homePageLnk, logoUrl });
        }

        /// <summary>
        /// 添加编辑用户信息动态 2-基本信息，3-详细信息，4-联系方式
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="type"></param>
        public void AddUserEditInfoTrack(string userId,int type)
        {
            ApiHelper.Instance.AppendTodayTrack(userId, typeof(FriendApplication), type, new string[] {});
        }

        /// <summary>
        /// 更新用户头像路径
        /// </summary>
        public void UpdateCurUserImageSrc()
        {
            User user = GetCurrentUser();
            user.PhotoFileName = user.UserId + ".png";
            //FIX ME:重构时需把下面的方法踢出去
            AddUserImageUpdateTrack(user.UserId);
            m_DataContext.SubmitChanges();
        }

        /// <summary>
        /// 根据用户名返回用户ID
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public string GetUserIdByUserName(string UserName)
        {
            IEnumerable<User> curUser = from u in m_DataContext.Users
                                        where u.FullName == UserName
                                        select u;
            return curUser.First<User>().UserId;
        }

        /// <summary>
        /// 得到所有省信息
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Province> GetProvinces()
        {
            IEnumerable<Province> provinces = from pro in m_DataContext.Provinces
                                              select pro;
            return provinces;
        }

        /// <summary>
        /// 得到所有城市通过省市ID
        /// </summary>
        /// <param name="provinceid"></param>
        /// <returns></returns>
        public IEnumerable<City> GetCitiesByProvinceId(int provinceid)
        {
            IEnumerable<City> cities = from city in m_DataContext.Cities
                                       where city.ProvinceId == provinceid
                                       select city;
            return cities;
        }

        /// <summary>
        /// 插入用户详细信息
        /// </summary>
        /// <param name="edubackground"></param>
        /// <param name="workexperience"></param>
        /// <param name="companyname"></param>
        /// <param name="companytype"></param>
        /// <param name="industrytype"></param>
        /// <param name="companyscale"></param>
        /// <param name="companyaddress"></param>
        /// <param name="department"></param>
        /// <param name="title"></param>
        /// <param name="postcode"></param>
        public void InsertUserDetailInfo(int edubackground, int workexperience, string companyname, int companytype, int industrytype, int companyscale, string companyaddress, string department, int title, string postcode, int cityid, string blog)
        {
            UsersDetail userdetail = new UsersDetail
            {
                UserId = GetCurrentUserId(),
                EduBackground = edubackground,
                WorkExperience = workexperience,
                CompanyName = companyname,
                CompanyTypeId = companytype,
                IndustryTypeId = industrytype,
                CompanyScale = companyscale,
                CompanyAddress = companyaddress,
                Department = department,
                TitleId = title,
                PostCode = postcode,
                BlogAddress = blog
            };
            m_DataContext.UsersDetails.InsertOnSubmit(userdetail);

            User user = GetCurrentUser();
            user.City = GetCityByCityId(cityid);
            AddUserEditInfoTrack(user.UserId, 3);
            m_DataContext.SubmitChanges();
        }

        /// <summary>
        ///更新用户详细信息 
        /// </summary>
        /// <param name="edubackground"></param>
        /// <param name="workexperience"></param>
        /// <param name="companyname"></param>
        /// <param name="companytype"></param>
        /// <param name="industrytype"></param>
        /// <param name="companyscale"></param>
        /// <param name="companyaddress"></param>
        /// <param name="department"></param>
        /// <param name="title"></param>
        /// <param name="postcode"></param>
        /// <param name="cityid"></param>
        public void UpdateUserDetailInfo(int edubackground, int workexperience, string companyname, int companytype, int industrytype, int companyscale, string companyaddress, string department, int title, string postcode, int cityid, string blog)
        {
            IEnumerable<UsersDetail> userdetails = from ud in m_DataContext.UsersDetails
                                                   where ud.UserId == GetCurrentUserId()
                                                   select ud;


            UsersDetail userdetail = userdetails.SingleOrDefault();
            userdetail.Dictionary3 = GetDictionarybyDictionaryId(edubackground);
            userdetail.Dictionary4 = GetDictionarybyDictionaryId(workexperience);
            userdetail.CompanyName = companyname;
            userdetail.Dictionary = GetDictionarybyDictionaryId(companytype);
            userdetail.Dictionary1 = GetDictionarybyDictionaryId(industrytype);
            userdetail.Dictionary5 = GetDictionarybyDictionaryId(companyscale);
            userdetail.CompanyAddress = companyaddress;
            userdetail.Department = department;
            userdetail.Dictionary2 = GetDictionarybyDictionaryId(title);
            userdetail.PostCode = postcode;
            userdetail.BlogAddress = blog;

            User user = GetCurrentUser();
            user.City = GetCityByCityId(cityid);
            AddUserEditInfoTrack(user.UserId, 3);
            m_DataContext.SubmitChanges();
        }

        /// <summary>
        /// 获得Dictionary对象ByDictionaryId
        /// </summary>
        /// <param name="did"></param>
        /// <returns></returns>
        private Dictionary GetDictionarybyDictionaryId(int did)
        {
            IEnumerable<Dictionary> dictionaries = from dic in m_DataContext.Dictionaries
                                                   where dic.DictionaryId == did
                                                   select dic;
            return dictionaries.SingleOrDefault();
        }

        /// <summary>
        /// 获得City对象ByCityId
        /// </summary>
        /// <param name="cityid"></param>
        /// <returns></returns>
        public City GetCityByCityId(int cityid)
        {
            IEnumerable<City> cities = from city in m_DataContext.Cities
                                       where city.CityId == cityid
                                       select city;
            return cities.SingleOrDefault();
        }
        /// <summary>
        /// 判断当前用户是否已经录入过详细个人信息
        /// </summary>
        /// <returns></returns>
        public bool UserDetailInfoExisted(string userid)
        {
            IEnumerable<UsersDetail> userdetail = from ud in m_DataContext.UsersDetails
                                                  where ud.UserId == userid
                                                  select ud;
            if (userdetail.Count() > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 判断当前用户是否已经录入过个人联系资料信息
        /// </summary>
        /// <returns></returns>
        public bool UserContactInfoExisted(string userid)
        {
            IEnumerable<UsersContact> usercontact = from uc in m_DataContext.UsersContacts
                                                    where uc.UserId == userid
                                                    select uc;
            if (usercontact.Count() > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 根据城市ID取得省
        /// </summary>
        /// <param name="cityid"></param>
        /// <returns></returns>
        public Province GetProvinceByCityId(int cityid)
        {
            IEnumerable<City> cities = from c in m_DataContext.Cities
                                       where c.CityId == cityid
                                       select c;
            City city = cities.SingleOrDefault();
            return city.Province;
        }

        /// <summary>
        /// 根据UserId得到用户
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public User GetUserByUserId(string userid)
        {
            IEnumerable<User> users = from u in m_DataContext.Users
                                      where u.UserId == userid
                                      select u;
            return users.SingleOrDefault();
        }


        /// <summary>
        /// 插入用户联系方式
        /// </summary>
        /// <param name="qq"></param>
        /// <param name="msn"></param>
        /// <param name="phone"></param>
        /// <param name="mobilephone"></param>
        /// <param name="fax"></param>
        public void InsertUserContactInfo(string qq, string msn, string phone, string mobilephone, string fax)
        {
            UsersContact usercontact = new UsersContact
            {
                UserId = GetCurrentUserId(),
                QQ = qq,
                MSN = msn,
                Phone = phone,
                MobilePhone = mobilephone,
                Fax = fax
            };
            m_DataContext.UsersContacts.InsertOnSubmit(usercontact);
            AddUserEditInfoTrack(UserRules._instance.GetCurrentUserId(), 4);
            m_DataContext.SubmitChanges();
        }

        /// <summary>
        /// 更新用户联系方式
        /// </summary>
        /// <param name="qq"></param>
        /// <param name="msn"></param>
        /// <param name="phone"></param>
        /// <param name="mobilephone"></param>
        /// <param name="fax"></param>
        public void UpdateUserContactInfo(string qq, string msn, string phone, string mobilephone, string fax)
        {
            IEnumerable<UsersContact> usercontacts = from uc in m_DataContext.UsersContacts
                                                     where uc.UserId == GetCurrentUserId()
                                                     select uc;

            UsersContact usercontact = usercontacts.SingleOrDefault();
            usercontact.QQ = qq;
            usercontact.MSN = msn;
            usercontact.Phone = phone;
            usercontact.MobilePhone = mobilephone;
            usercontact.Fax = fax;
            AddUserEditInfoTrack(UserRules._instance.GetCurrentUserId(), 4);
            m_DataContext.SubmitChanges();
        }

        /// <summary>
        /// 更新用户隐私设置
        /// </summary>
        /// <param name="userrules"></param>
        public void UpdateUserPrivacySetting(string userrules)
        {
            User user = GetCurrentUser();
            user.PrivacySettings = userrules;
            m_DataContext.SubmitChanges();
        }
    }
}
